package cn.iocoder.yudao.module.voice.cc.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.zhongweixian.listener.ConnectionListener;
import org.zhongweixian.server.websocket.WebSocketServerHandler;

import java.net.InetSocketAddress;
import java.util.concurrent.CopyOnWriteArraySet;
@Slf4j
public class WsServer {

    private Integer heart = 60;
    private ListenerCallBack connectionListener;
    public static final CopyOnWriteArraySet<Channel> WEB_SOCKET_CHANNEL_SET = new CopyOnWriteArraySet<>();

    public WsServer(Integer heart,ListenerCallBack connectionListener) {
        this.heart = heart;
        this.connectionListener = connectionListener;
    }
        public void start(InetSocketAddress socketAddress) {
            // 主线程组
            NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
            //工作线程组
            NioEventLoopGroup workGroup = new NioEventLoopGroup(200);
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                    .group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new HttpObjectAggregator(64 * 1024));
                            pipeline.addLast(new ChunkedWriteHandler());
                            pipeline.addLast(new WebSocketServerProtocolHandler("/"));
                            pipeline.addLast(new WsServerHandler(WsServer.this.heart, WsServer.this.connectionListener));
                        }
                    });
            try {
                ChannelFuture future = serverBootstrap.bind(socketAddress).sync();
                System.out.println("开启 port:" + socketAddress.getPort());
                future.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                bossGroup.shutdownGracefully();
                workGroup.shutdownGracefully();
            }
        }
    }

